package com.project.srtp.secure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.srtp.secure.dto.req.SignedPreKeyReqDTO;
import com.project.srtp.secure.dao.entity.SignedPreKeyDO;
import com.project.srtp.secure.dao.mapper.SignedPreKeyMapper;
import com.project.srtp.secure.service.SignedPreKeyService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 曹行阳
 * @version 0.1
 * @date 2025/6/16 12:16
 */
@Service

public class SignedPreKeyServiceImpl extends ServiceImpl<SignedPreKeyMapper, SignedPreKeyDO> implements SignedPreKeyService {
    @Override
    @Transactional
    public void storeSignedPreKey(SignedPreKeyReqDTO signedPreKey, String userId) {
        SignedPreKeyDO spkDO = SignedPreKeyDO.builder()
                .userId(userId)
                .keyId(signedPreKey.getId())
                .publicKey(signedPreKey.getPublicKey())
                .signature(signedPreKey.getSignature())
                .cipher(signedPreKey.getCipher())
                .salt(signedPreKey.getSalt())
                .active(true)
                .timestamp(signedPreKey.getTimestamp())
                .build();

        try {
            int updated = baseMapper.update(
                    spkDO,
                    new UpdateWrapper<SignedPreKeyDO>()
                            .eq("user_id", userId)
                            .eq("key_id", signedPreKey.getId())
            );
            if (updated == 0) {
                baseMapper.insert(spkDO);
            }
        } catch (DuplicateKeyException ex) {
            log.error("SignedPreKey already exists");
        }
    }

    @Override
    public SignedPreKeyDO selectSignedPreKeyByUserId(String userId) {
        LambdaQueryWrapper<SignedPreKeyDO> queryWrapper = Wrappers.lambdaQuery(SignedPreKeyDO.class)
                .eq(SignedPreKeyDO::getUserId, userId)
                .eq(SignedPreKeyDO::getActive, true);
        try {
            return baseMapper.selectOne(queryWrapper);
        } catch (Exception e) {
            log.error("用户不存在");
        }
        return null;
    }
}
